package com.kl.modular.sysman.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kl.common.pager.PageParameter;
import com.kl.common.pager.Pager;
import com.kl.common.util.EncryptionUtil;
import com.kl.common.util.UUIDUtil;
import com.kl.modular.common.controller.BaseController;
import com.kl.modular.common.response.ResponseBase;
import com.kl.modular.sysman.system.constant.ResponsePath;
import com.kl.modular.system.dao.bo.SystemAdminBo;
import com.kl.modular.system.dao.bo.SystemAdminRoleBo;
import com.kl.modular.system.dao.bo.SystemRoleBo;
import com.kl.modular.system.dao.model.SystemAdmin;
import com.kl.modular.system.dao.model.SystemAdminRole;
import com.kl.modular.system.dao.model.SystemAuthResource;
import com.kl.modular.system.dao.model.SystemRole;
import com.kl.modular.system.service.api.ISystemAdminRoleService;
import com.kl.modular.system.service.api.ISystemAdminService;
import com.kl.modular.system.service.api.ISystemLogService;
import com.kl.modular.system.service.api.ISystemRoleService;
import com.kl.modular.system.service.constant.SystemConStant;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 用户Controller
 * @author kongling_zjb
 * @time 2016/7/26 16:47
 *
 */
@Controller
public class SystemAdminController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SystemAdminController.class);

	@Autowired
	private ISystemAdminService systemAdminService;
	
	@Autowired
	private ISystemRoleService systemRoleService;
	
	@Autowired
	private ISystemAdminRoleService systemAdminRoleService;

	@Autowired
	private ISystemLogService systemLogService;

	/**
	 * 用户列表页面
	 */

	@RequestMapping(value = "/sysman/systemAdmin/toAdminlist", method = RequestMethod.GET)
	@RequiresPermissions("sysman:SYSTEM_ADMIN_MAN:viewlist")
	public String toSystemAdminList(HttpServletRequest request) {
		logger.info("用户列表页面");
		SystemRoleBo roleBo = new SystemRoleBo();
		List<SystemRole> systemRoleList = systemRoleService.getListByBo(roleBo);
		request.setAttribute("systemRoleList", systemRoleList);
		return ResponsePath.GUESTSTARPOINT_SYSTEM_ADMIN_LIST;
	}

	/**
	 * 用户列表数据
	 */
	@RequestMapping(value = "/sysman/systemAdmin/adminList", method = RequestMethod.POST)
	@RequiresPermissions("sysman:SYSTEM_ADMIN_MAN:viewlist")
	public String systemAdminList(SystemAdminBo bo, PageParameter pageParameter, HttpServletRequest request) {
		logger.info("用户列表数据>>data:" + JSON.toJSONString(bo));
		if (bo == null) {
			bo = new SystemAdminBo();
		}
		Pager<SystemAdmin> systemAdminList = systemAdminService.getListByBo(bo, pageParameter);
		request.setAttribute("pager", systemAdminList);
		return ResponsePath.GUESTSTARPOINT_SYSTEM_ADMIN_AJAX_LIST;
	}

	/**
	 * 添加页面
	 */
	@RequestMapping(value = "/sysman/systemAdmin/toAdd", method = RequestMethod.GET)
	@RequiresPermissions("sysman:SYSTEM_ADMIN_MAN:add")
	public String toAdd(HttpServletRequest request) {
		logger.info("添加用户页面");
		SystemRoleBo roleBo = new SystemRoleBo();
		roleBo.setRoleModuleType(SystemAuthResource.AUTH_MODULE_SYS);
		List<SystemRole> systemRoleList = systemRoleService.getListByBo(roleBo);
		request.setAttribute("systemRoleList", systemRoleList);
		return ResponsePath.GUESTSTARPOINT_SYSTEM_ADD_ADMIN;
	}

	/**
	 * 添加用户
	 */
	@RequestMapping(value = "/sysman/systemAdmin/addSystemAdmin", method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions("sysman:SYSTEM_ADMIN_MAN:add")
	public String addSystemAdmin(SystemAdmin admin , String roleCodes ,HttpServletRequest request) throws Exception {
		logger.info("添加用户>>data:" + JSON.toJSONString(admin));

		ResponseBase base = new ResponseBase();

		// 数据验证
		if (admin == null) {
			logger.error("添加用户数据验证>>admin is null");
			base.setMsg(ResponseBase.RESPOSNE_NOT_VALID_ERROR);
			return JSON.toJSONString(base);
		}
		// 验证用户名
		if (StringUtils.isEmpty(admin.getSystemUserName())) {
			logger.error("添加用户数据验证>>systemUserName is null");
			base.setMsg("用户名不能为空");
			return JSON.toJSONString(base);
		}
		// 验证密码
		if (StringUtils.isEmpty(admin.getSystemPassword())) {
			logger.error("添加用户数据验证>>systemPassword is null");
			base.setMsg("密码不能为空");
			return JSON.toJSONString(base);
		}
		// 验证角色
		if(StringUtils.isEmpty(roleCodes)){
			logger.error("添加用户数据验证>>roleCodes is null");
			base.setData("请至少选择一个角色");
			return JSON.toJSONString(base);
		}

		String [] roles = roleCodes.split(",");
		if(roles == null || roles.length == 0){
			logger.error("添加用户数据验证>>roles is null");
			base.setData("请至少选择一个角色");
			return JSON.toJSONString(base);
		}
		
		// 密码加密
		String key = EncryptionUtil.getKey();
		String datpwd = EncryptionUtil.encrypt(admin.getSystemPassword(), key);
		admin.setSystemSalt(key);
		admin.setSystemPassword(datpwd);
		admin.setSystemCode(UUIDUtil.getUniquekey());
		admin.setStatus(SystemConStant.SYSTEM_ADMIN_STATUS_NORMAL);
		systemAdminService.addSystemAdmin(admin , roles);
		base.setStatus(ResponseBase.RESPONSE_STATUS_SUCCESS);
		String jsonstr = JSON.toJSONString(base);
		logger.info("添加用户>>返回>>data:" + jsonstr);
		return jsonstr;
	}

	/**
	 * 修改页面
	 */
	@RequestMapping(value = "/sysman/systemAdmin/toChangeView", method = RequestMethod.GET)
	@RequiresPermissions("sysman:SYSTEM_ADMIN_MAN:edit")
	public String toChangeSystemAdmin(String code, HttpServletRequest request) throws Exception {
		logger.info("用户修改页面>>data:" + code);
		SystemAdmin systemAdmin = systemAdminService.getSystemAdminByCode(code);
		SystemAdminRoleBo adminRoleBo = new SystemAdminRoleBo();
		adminRoleBo.setAdminCode(systemAdmin.getSystemCode());
		List<SystemAdminRole> adminRoleList = systemAdminRoleService.getListByBo(adminRoleBo);
		StringBuffer adminRoleStr = new StringBuffer();
		if(adminRoleList!=null&&adminRoleList.size()!=0){
			for(int i = 0;i<adminRoleList.size();i++){
				SystemAdminRole adminRole = adminRoleList.get(i);
				if(adminRole == null){
					continue;
				}
				adminRoleStr.append(adminRole.getRoleCode());
				if(StringUtils.isEmpty(adminRoleStr.toString())){
					adminRoleStr.append(",");
				}
			}
		}
		SystemRoleBo roleBo = new SystemRoleBo();
		roleBo.setRoleModuleType(SystemAuthResource.AUTH_MODULE_SYS);
		List<SystemRole> systemRoleList = systemRoleService.getListByBo(roleBo);
		request.setAttribute("systemRoleList", systemRoleList);
		request.setAttribute("adminRoles", adminRoleStr.toString());
		request.setAttribute("item", systemAdmin);
		return ResponsePath.GUESTSTARPOINT_SYSTEM_UPCHANGE_ADMIN;
	}

	/**
	 * 更新用户信息
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/sysman/systemAdmin/upChange", method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions("sysman:SYSTEM_ADMIN_MAN:edit")
	public String upChangeSystemAdmin(SystemAdmin admin, String roleCodes, HttpServletRequest request) throws Exception {
		logger.info("更新用户信息>>data:" + JSON.toJSONString(admin));

		ResponseBase base = new ResponseBase();

		// 数据验证
		if (admin == null) {
			logger.error("更新用户数据验证>>admin is null");
			base.setMsg(ResponseBase.RESPOSNE_NOT_VALID_ERROR);
			return JSON.toJSONString(base);
		}
		// 验证唯一标识
		if (StringUtils.isEmpty(admin.getSystemCode())) {
			logger.error("更新用户数据验证>>systemCode is null");
			base.setMsg("用户唯一标识不能为空");
			return JSON.toJSONString(base);
		}
		// 验证角色
		if(StringUtils.isEmpty(roleCodes)){
			logger.error("添加用户数据验证>>roleCodes is null");
			base.setData("请至少选择一个角色");
			return JSON.toJSONString(base);
		}

		String [] roles = roleCodes.split(",");
		if(roles == null || roles.length == 0){
			logger.error("添加用户数据验证>>roles is null");
			base.setData("请至少选择一个角色");
			return JSON.toJSONString(base);
		}

		systemAdminService.updateByCode(admin,roles);

		base.setStatus(ResponseBase.RESPONSE_STATUS_SUCCESS);
		String jsonstr = JSON.toJSONString(base);
		logger.info("编辑用户信息>>返回>>data:" + jsonstr);
		return jsonstr;
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/sysman/systemAdmin/delSystemAdmin", method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions("sysman:SYSTEM_ADMIN_MAN:delete")
	public String delSystemAdmin(String id, HttpServletRequest request) throws Exception {
		logger.info("删除用户>>data:" + JSON.toJSONString(id));
		ResponseBase base = new ResponseBase();

		// 数据验证
		if (StringUtils.isEmpty(id)) {
			logger.error("数据验证>>删除 codes is null");
			base.setMsg("请求数据有误");
			return JSON.toJSONString(base);
		}

		String[] codestrs = id.split(",");

		if (codestrs == null || codestrs.length == 0) {
			logger.error("数据验证>>删除用户资源>>codestrs is null");
			base.setMsg("参数错误，请选择要删除的用户");
			return JSON.toJSONString(base);
		}

		systemAdminService.deleteByCode(codestrs);
		base.setStatus(ResponseBase.RESPONSE_STATUS_SUCCESS);

		String jsonstr = JSON.toJSONString(base);
		logger.info("删除用户资源>>返回view>>data:" + jsonstr);
		return jsonstr;
	}

	/**
	 * 检查用户名是否存在
	 * @param systemUserName
	 * @return
	 */
	@RequestMapping(value = "/sysman/systemAdmin/checkUserName" , method = RequestMethod.POST)
	public void checkUserName(String systemUserName,HttpServletResponse response)throws IOException {
		JSONObject json = new JSONObject();
		try{
			if(StringUtils.isEmpty(systemUserName)){
				json.put("error", "用户名已存在，请更换");
				return;
			}
			SystemAdminBo systemAdminBo = new SystemAdminBo();
			systemAdminBo.setAdminUserName(systemUserName);
			int result = systemAdminService.findAdminCountByBo(systemAdminBo);
			json.put("ok","");
			if(result != 0){
				json.put("error", "用户名已存在，请更换");
			}
		}finally{
			response.setContentType("application/json;charset=utf-8");
			PrintWriter writer;
			try {
				writer = response.getWriter();
				writer.print(json.toString());
				writer.flush();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * TO 重置密码
	 * @return
	 */
	@RequestMapping(value = "/sysman/systemAdmin/toResetPwd" , method = RequestMethod.GET)
	@RequiresPermissions("sysman:SYSTEM_ADMIN_MAN:resetPwd")
	public String toResetPwd(String systemCode ,HttpServletRequest request){
		SystemAdmin admin = systemAdminService.getSystemAdminByCode(systemCode);
		request.setAttribute("admin" ,admin);
		return ResponsePath.GUESTSTARPOINT_SYSTEM_RESETPWD_ADMIN;
	}

	/**
	 * 重置密码
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/sysman/systemAdmin/resetPwd" , method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions("sysman:SYSTEM_MAN:resetPwd")
	public String resetPwd(String systemCode ,String systemPwd, HttpServletRequest request) throws Exception{
		ResponseBase rsp = new ResponseBase();
		if(StringUtils.isEmpty(systemCode)||StringUtils.isEmpty(systemPwd)){
			rsp.setMsg("参数错误，重置失败");
			return JSON.toJSONString(rsp);
		}
		SystemAdmin admin = systemAdminService.getSystemAdminByCode( systemCode);
		if(admin == null){
			rsp.setMsg("参数错误，重置失败");
			return JSON.toJSONString(rsp);
		}
		// 密码加密
		String key = EncryptionUtil.getKey();
		String datpwd = EncryptionUtil.encrypt(systemPwd, key);
		admin.setSystemSalt(key);
		admin.setSystemPassword(datpwd);
		systemAdminService.updatePwdByCode(admin);

		rsp.setStatus(ResponseBase.RESPONSE_STATUS_SUCCESS);
		return JSON.toJSONString(rsp);
	}


    /**
     * 修改密码页面
     * @return
     */
	@RequestMapping(value = "/sysman/systemAdmin/editPwdView" , method = RequestMethod.GET)
    @RequiresPermissions("sysman:UPDATE_PWD:viewAndEdit")
	public String editPwdView(){
        return ResponsePath.GUESTSTARPOINT_SYSTEM_EDITPWD_ADMIN;
    }


	/**
	 * 修改密码
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/sysman/systemAdmin/editPwd" , method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions("sysman:UPDATE_PWD:viewAndEdit")
	public String editPwd(String oldPassword, String password ,HttpServletRequest request) throws Exception{
		ResponseBase base = new ResponseBase();

        if(StringUtils.isEmpty(oldPassword)){
            base.setMsg("原始密码不能为空");
            return JSON.toJSONString(base);
        }
        if(StringUtils.isEmpty(password)){
			base.setMsg("新密码不能为空");
			return JSON.toJSONString(base);
		}
		// 原始密码判断
        SystemAdmin systemAdminData = systemAdminService.getSystemAdminByCode(getAuthUserAdminId());
        if(systemAdminData == null){
            base.setMsg("当前登录人信息有误,请重新登录");
            return JSON.toJSONString(base);
        }
        boolean pans = EncryptionUtil.decrypt(oldPassword,systemAdminData.getSystemSalt(),systemAdminData.getSystemPassword());
        if(!pans){
            base.setMsg("原始密码错误，请重新输入");
            return JSON.toJSONString(base);
        }
		String salt = EncryptionUtil.getKey();
		String pwd = EncryptionUtil.encrypt(password, salt);
		SystemAdmin systemAdmin = new SystemAdmin();
		systemAdmin.setSystemCode(getAuthUserAdminId());
		systemAdmin.setSystemPassword(pwd);
		systemAdmin.setSystemSalt(salt);
		systemAdminService.updatePwdByCode(systemAdmin);

		base.setStatus(ResponseBase.RESPONSE_STATUS_SUCCESS);
		String jsonstr = JSON.toJSONString(base);
		logger.info("修改密码>>返回：data:"+jsonstr);
		return jsonstr;
	}

}
